#!/usr/bin/env python3
# -*- coding: utf-8 -*-


__autho__ = "Tony.Don"
__lastupdatetime__ = "2017/09/29"

import queue
import threading
from core.pool import pool
from application.feedpage import feed
from core.Enum import Enum
from core.event import eventmanager

'''
class
    core.spiderThread.spiderThread(eventmanager)
description
    蜘蛛线程池
'''
class spiderThread(eventmanager):
    #队列总数
    __threadCount__=0
    __taskCount__=0
    #当前使用数
    __scaler__=0
    __runTask__=0
    #对象列表
    __poollist__=None
    __tasklist__=None
    __event__ = Enum(["ADD_TASK","COMPLETE"])
    __lock=threading.RLock()
    def __init__(self,maxThread,taskCount):
        self.__poollist__=pool()
        self.addlisten("ADD_TASK",self.work)
        self.__tasklist__=queue.Queue(maxsize=taskCount)
        for o in range(maxThread):
            self.__lock.acquire()
            self.__poollist__.push(feed(self))
            self.__lock.release()
            
    def addTask(self,url,ruleName):
        if not self.__tasklist__.full():
            self.__lock.acquire()
            self.__tasklist__.put([url,ruleName])
            self.__lock.release()
            self.triggerevent("ADD_TASK")()
            
    def getTask(self):
        try:
            self.__lock.acquire()
            if not self.__tasklist__.empty():
                return self.__tasklist__.get()
            else:
                return None
        except Exception as e:
            print(e)
        finally:
            self.__lock.release()

    def complete(self,args):
        try:
            self.__lock.acquire()
            self.__poollist__.push(args) 
            self.__scaler__-=1
            self.__runTask__-=1
            func=self.triggerevent("COMPLETE")
            if func:
                func()
        except Exception as e:
            print(e)
        finally:
            self.__lock.release()
    def work(self):
        try:
            self.__lock.acquire()
            func=self.__poollist__.pop()
            self.__runTask__+=1
            self.__scaler__+=1
            if func:
                if not func.isAlive():
                    func.start()
        except Exception as e:
            print(e)
        finally:
            self.__lock.release()